

import { Inject, Provide } from '@midwayjs/core';
import { RespInfo, RespStatusCode } from '../types/common.type';
import { RespMethod } from '../util/common.method';
import { createTransport } from 'nodemailer';
import { JwtService } from '@midwayjs/jwt';
import { InjectEntityModel } from '@midwayjs/typegoose';
import { User } from '../entity/user';
import { ReturnModelType } from '@typegoose/typegoose';

@Provide()
export class EmailService {
  private transporter = null;

  @Inject()
  jwtService: JwtService;

  @InjectEntityModel(User)
  userModel: ReturnModelType<typeof User>;

  constructor() {
    this.transporter = createTransport({
      // 邮箱服务的host: qq: smtp.qq.com; 163: smtp.163.com
      host: 'smtp.qq.com',
      auth: {
        user: '455422060@qq.com', //  发件人邮箱
        pass: 'yrkclblyirssbjbh' //  授权码
      },
      tls: {
        rejectUnauthorized: false, // 拒绝认证就行了， 不然会报证书问题
      },
    });
  }

  /** 发送注册验证码 */
  sendRegisterCode(to: string, code: string, subject: string = '您好，欢迎来到 With_Hope 世界'): Promise<RespInfo> {
    return new Promise<RespInfo>(async reslove => {
      if (await this.userModel.findOne({ email: to })) {
        reslove(RespMethod({}, RespStatusCode.Error, '该邮箱已被注册'))
      } else {
        this.transporter.sendMail({
          from: '455422060@qq.com',
          to, subject,
          html: this.getRegisterTemplate(code, '你正在进行注册操作。'),
        }, (err) => {
          if (err) {
            reslove(RespMethod({}, RespStatusCode.Error, String(err)))
          } else {
            const secret = this.jwtService.signSync({ code, email: to })
            reslove(RespMethod({ secret }))
          }
        })
      }
    })
  }

  /** 发送找回密码验证码 */
  sendForgotPasswordCode(to: string, code: string, subject: string = '您好，欢迎来到 With_Hope 世界'): Promise<RespInfo> {
    return new Promise<RespInfo>(async reslove => {
      if (!await this.userModel.findOne({ email: to })) {
        reslove(RespMethod({}, RespStatusCode.Error, '该邮箱未注册'))
      } else {
        this.transporter.sendMail({
          from: '455422060@qq.com',
          to, subject,
          html: this.getRegisterTemplate(code, '你正在进行找回密码操作。'),
        }, (err) => {
          if (err) {
            reslove(RespMethod({}, RespStatusCode.Error, String(err)))
          } else {
            const secret = this.jwtService.signSync({ code, email: to })
            reslove(RespMethod({ secret }))
          }
        })
      }
    })
  }


  /** 通用邮箱模板 */
  getRegisterTemplate(code: string, remark?: string): string {
    return `<includetail>
    <div align="center">
      <table width="99%" border="0" cellspacing="0" cellpadding="0"
        style="padding-bottom: 20px;max-width: 660px;min-width: 320px;margin: 0 auto;">
        <tbody>
          <tr>
            <td bgcolor="#212429" style="background-color: #fff;">
              <div
                style="width: 100%;display: flex; flex-direction: column;align-items: center;padding: 20px;box-sizing: border-box; font-size: 14px;border-style: solid;border-width: thin;border-color: #dadce0;border-radius: 8px;padding: 40px 20px;">
                <img src="https://tool.lxyy.fun/assets/logo-53320f18.png" alt="" width="200px">
                <h4>您本次操作所需的验证码 为：</h4>
                <span
                  style="  border-radius: 7px;  padding: 30px 50px;font-size: 30px; font-weight: 600; letter-spacing: 10px;">
                  `+ code + ` </span>
                <div style="margin-top: 20px; font-size: 12px; color: #373737;">验证码有效期 5 分钟</div>
                <div style="margin-top: 10px; font-size: 12px; color: #8d8d8d;">如非本人操作，请忽略此邮件。祝您生活愉快</div>
                <div style="margin-top: 10px; font-size: 12px; color: #8d8d8d;">` + remark + `有疑问？ 请联系 <span
                    style="color: #00a2ff;">455422060@qq.com</span></div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </includetail>`
  }
}